package com.example.stars_project_android.index;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;

import com.example.stars_project_android.R;
import com.example.stars_project_android.entity.SpaceTime;
import com.example.stars_project_android.fragment.GuestbookFragment;
import com.example.stars_project_android.fragment.HomeFragment;
import com.example.stars_project_android.fragment.MsgPageFragment;
import com.example.stars_project_android.fragment.UserFragment;
import com.example.stars_project_android.util.Constant;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页的界面
 */
public class Index extends AppCompatActivity {

    //定义变量的属性
    private BottomNavigationView mNavigationView;
    private FragmentManager mFragmentManager;
    private Fragment[] fragments;
    private int lastFragment;

    private int code;   //返回的状态码
    private String msgCon;  //返回的信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            try {
                JSONObject jsonObject = new JSONObject(result);
                code = jsonObject.getInt("code");
                msgCon = jsonObject.getString("msg");
                Log.e("状态码", code + "");
                Log.e("返回的提示信息：", msgCon);
                if (code == 200) {
                    if (Constant.roomList.size() != 0){
                        Constant.roomList.clear();
                    }

                    JSONObject jsonObject1 = jsonObject.getJSONObject("date");
                    JSONArray jsonArray = jsonObject1.getJSONArray("content");
                    for (int i = 0; i < jsonArray.length(); i++){
                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                        SpaceTime spaceTime = new SpaceTime();
                        spaceTime.setRoomId(jsonObject2.getString("roomId"));
                        spaceTime.setCreateTime(jsonObject2.getString("createTime"));
                        spaceTime.setRoomName(jsonObject2.getString("roomName"));
                        spaceTime.setUserCountMax(jsonObject2.getInt("userCountMax"));
                        spaceTime.setUserCountCurrent(jsonObject2.getInt("userCountCurrent"));
                        spaceTime.setUserPhone(jsonObject2.getString("userPhone"));
                        spaceTime.setRoomDescribe(jsonObject2.getString("roomDescribe"));
                        spaceTime.setRoomAttribute(jsonObject2.getString("roomAttribute"));
                        spaceTime.setRoomState(jsonObject2.getString("roomState"));

                        Constant.roomList.add(spaceTime);
                    }
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        //绑定布局控件
        mNavigationView = findViewById(R.id.main_navigation_bar);
        initFragment();
        initListener();

    }

    /**
     * 在从activity返回时调用
     */
    @Override
    protected void onResume() {
        int id = getIntent().getIntExtra("index", 0);
        switchFragment(lastFragment,id);
        super.onResume();
    }

    private void initFragment() {
        //首页
        HomeFragment mHomeFragment = new HomeFragment();
        //留言板
        GuestbookFragment guestbookFragment = new GuestbookFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.main_page_controller,guestbookFragment).commit();
        //时空门
        Fragment fragment = new Fragment();
        //消息
        MsgPageFragment msgFragment = new MsgPageFragment();
        //我的
        UserFragment userFragment = new UserFragment();
//        getSupportFragmentManager().beginTransaction().add(R.id.main_page_controller,userFragment).commit();

        fragments = new Fragment[]{
                mHomeFragment, guestbookFragment, fragment, msgFragment, userFragment
        };
        mFragmentManager = getSupportFragmentManager();
        //默认显示HomeFragment
        mFragmentManager.beginTransaction()
                .replace(R.id.main_page_controller, mHomeFragment)
                .show(mHomeFragment)
                .commit();
    }

    private void initListener() {
        mNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.home:
                        if (lastFragment != 0) {
                            Index.this.switchFragment(lastFragment, 0);
                            lastFragment = 0;
//                            getConn(item.getTitle().toString());
                        }
                        return true;
                    case R.id.chat:
                        if (lastFragment != 1) {
                            Index.this.switchFragment(lastFragment, 1);
                            lastFragment = 1;
//                            getConn(item.getTitle().toString());
                        }
                        return true;
                    case R.id.space:
                        if (lastFragment != 2) {
                            Index.this.switchFragment(lastFragment, 2);
                            lastFragment = 2;
//                            getConn(item.getTitle().toString());
                        }
                        return true;
                    case R.id.msg:
                        if (lastFragment != 3) {
                            Index.this.switchFragment(lastFragment, 3);
                            lastFragment = 3;
//                            getConn(item.getTitle().toString());
                        }
                        return true;
                    case R.id.user:
                        if (lastFragment != 4) {
                            Index.this.switchFragment(lastFragment, 4);
                            lastFragment = 4;
//                            getConn(item.getTitle().toString());
                        }
                        return true;
                }
                return false;
            }
        });
    }

    /**
     * 显示fragment
     * @param lastFragment
     * @param index
     */
    private void switchFragment(int lastFragment, int index) {
        if (index == 2){
            Intent intent = new Intent(this,im.zego.gomovie.client.movielist.JoinMovieRoomActivity.class);
            startActivity(intent);
        }else{
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            transaction.hide(fragments[lastFragment]);
            if (!fragments[index].isAdded()){
                transaction.add(R.id.main_page_controller,fragments[index]);
            }
            transaction.show(fragments[index]).commitAllowingStateLoss();
        }

    }

    /**
     * 获取网络连接
     */
    private void getConn(String msg) {
        //向后端传递获取的信息
        //将数据封装
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(msg,msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("json格式",jsonObject.toString());
//        MediaType type = MediaType.parse("application/json;charset=utf-8");
//        RequestBody requestBody = RequestBody.create(type,""+jsonObject.toString());

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://192.168.1.7:8080/room/findRoomByAttribute?roomAttribute="+msg)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("okhttp","请求成功");
                //处理后端的数据
                response = okHttpClient.newCall(request).execute();
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}